<!--
 * @页面名称:字段规则
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="form-tab2">
    <!-- 按钮组 -->
    <div class="button-group">
      <el-row>
        <el-col :span="6" class="input-search">
          <el-input placeholder="请输入关键字查询" v-model="searchString" @change="onSearchChange"></el-input>
        </el-col>
        <el-col :span="4">
          <el-tooltip class="box-item" placement="bottom-end">
            <template #content>
              <span>添加界面</span>
            </template>
            <el-button :disabled="BtnStatus[0]" :icon="FolderAdd" @click="add"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" placement="bottom-end">
            <template #content>
              <span>修改界面</span>
            </template>
            <el-button :disabled="BtnStatus[1]" :icon="Edit" @click="edit"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" placement="bottom-end">
            <template #content>
              <span>删除界面</span>
            </template>
            <el-button :disabled="BtnStatus[2]" :icon="Delete" @click="del"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>
    </div>
    <!-- 表格模块 -->
    <stable :columns="tableSetting.columns" :data="tableSetting.data" @rowClick="rowClick"></stable>
    <!-- 新增修改弹出框 -->
    <el-dialog v-model="dialogSetting.visible" :title="dialogSetting.title" width="30%" draggable>
      <el-form label-width="90px" :model="formData" :rules="rules" ref="formRef">
        <el-form-item label="数据表字段:" prop="TableField">
          <el-select v-model="formData.TableField" filterable>
            <el-option
              v-for="item in column"
              :key="item.TableId"
              :label="item.DDM_CNName + '(' + item.Field_Name + ')'"
              :value="item.Field_Name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则类行:" prop="RuleType">
          <el-select v-model="formData.RuleType">
            <el-option label="init" value="init" />
            <el-option label="trigger" value="trigger" />
            <el-option label="display" value="display" />
            <el-option label="orderby" value="orderby" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:" prop="Status">
          <el-select v-model="formData.Status">
            <el-option label="档案收集" value="档案收集" />
            <el-option label="档案整理" value="档案整理" />
            <el-option label="档案保存" value="档案保存" />
            <el-option label="档案利用" value="档案利用" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用:" prop="Enable">
          <el-checkbox v-model="formData.Enable"></el-checkbox>
        </el-form-item>
        <el-form-item label="字段规则:" prop="Rule">
          <el-input v-model="formData.Rule" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="说明:" prop="Remark">
          <el-input v-model="formData.Remark"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="handle"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, nextTick } from "vue";
import { FolderAdd, Edit, Delete } from "@element-plus/icons-vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { FormInstance, FormRules } from "element-plus";
// 按钮状态
const BtnStatus = ref([true, true, true]);
const { proxy } = useCurrentInstance();
// 搜索字段
const searchString = ref("");
// 父级表格保存对象
const tabClickFromParent = ref();
// 表格配置
const tableSetting = reactive({
  columns: [
    { title: "数据表字段", field: "FR_TableField", sortable: true },
    { title: "数据表中文字段说明", field: "CName", sortable: true },
    { title: "数据表状态", field: "FR_Status", sortable: true },
    { title: "规则类别", field: "FR_RuleType", sortable: true },
    { title: "字段规则", field: "FR_Rule", sortable: true },
    {
      title: "启用",
      field: "FR_Enable",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<el-checkbox disabled v-model={row.FR_Enable} />];
        }
      }
    },
    { title: "说明", field: "FR_Remark", sortable: true }
  ],
  data: [] as any[],
  sourthTableData: [] as any[] //源数据
});
// 表格单击保存对象
const clickObj = ref();
// 弹出框配置
const dialogSetting = reactive({
  visible: false,
  title: ""
});
// 表单绑定字段
const formData = reactive({
  TableField: "",
  RuleType: "",
  Rule: "",
  Status: "",
  Enable: true,
  Remark: ""
});
// 表单规则
const rules = reactive<FormRules>({
  DDM_CNName: [{ required: true, message: "请输入中文名称!", trigger: "blur" }],
  Field_Name: [{ required: true, message: "请选择数据表字段!", trigger: "blur" }]
});
// 表单实例
const formRef = ref<FormInstance>();
// 数据表字段保存
const column = ref<any>([]);
// 获取表格数据
const getTableData = async (record: any) => {
  if (!record) {
    return;
  }
  tabClickFromParent.value = record;
  await getColumn();
  proxy.$vueAxios
    .post("Master_Base_FieldRule/GetConditional", {
      order: "FR_Order asc",
      dtoList: [{ fieldName: "FMT_ID", fieldValue: record.FMT_ID }]
    })
    .then((res: any) => {
      tableSetting.data = res.List;
      tableSetting.sourthTableData = res.List; // 保留源数据作为搜索用
      tableSetting.data.forEach((item: any) => {
        const data = column.value.find((v: any) => v.Field_Name === item.FR_TableField);
        item.CName = data.DDM_CNName;
      });
      BtnStatus.value[0] = false;
    });
};
// 获取界面显示字段数据
const getColumn = async () => {
  await proxy.$vueAxios
    .post(
      "Master_Base_Data_Disp_Mstr/GetConditional",
      {
        order: "DDM_Order asc",
        dtoList: [{ fieldName: "FMT_ID", fieldValue: tabClickFromParent.value.FMT_ID }]
      },
      { noLoading: true }
    )
    .then((res: any) => {
      column.value = res.List;
    });
};
// 表格单击事件
const rowClick = ({ row }: any) => {
  BtnStatus.value[1] = false;
  BtnStatus.value[2] = false;
  clickObj.value = row;
};
// 新增事件
const add = () => {
  formRef.value?.resetFields();
  dialogSetting.visible = true;
  dialogSetting.title = "新增";
};
// 修改事件
const edit = () => {
  dialogSetting.visible = true;
  dialogSetting.title = "修改";
  nextTick(() => {
    formData.Enable = clickObj.value.FR_Enable;
    formData.Rule = clickObj.value.FR_Rule;
    formData.RuleType = clickObj.value.FR_RuleType;
    formData.Status = clickObj.value.FR_Status;
    formData.TableField = clickObj.value.FR_TableField;
    formData.Remark = clickObj.value.FR_Remark;
  });
};
// 删除事件
const del = () => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios.post("Master_Base_FieldRule/Delete", [clickObj.value.FR_ID]).then((res: any) => {
        if (res.Mark) {
          tableSetting.data = tableSetting.data.filter(
            (v: any) => v !== tableSetting.data.find((v: any) => v.FR_ID === clickObj.value.FR_ID)
          );
          proxy.$message.success("删除成功");
        } else {
          proxy.$message.error("删除失败");
        }
      });
    })
    .catch(err => {
      console.log(err);
      proxy.$message("取消删除");
    });
};
// 新增修改确认事件
const handle = () => {
  formRef.value!.validate((isValid: boolean) => {
    if (isValid) {
      if (dialogSetting.title === "新增") {
        const param = {
          fR_ID: proxy.$global.createID(),
          fmT_ID: tabClickFromParent.value.FMT_ID,
          fR_TableField: formData.TableField,
          fR_RuleType: formData.RuleType,
          fR_Rule: formData.Rule,
          fR_Enable: formData.Enable,
          fR_Status: formData.Status,
          fR_Remark: formData.Remark
        };
        proxy.$vueAxios.post("Master_Base_FieldRule", param).then(() => {
          dialogSetting.visible = false;
          getTableData(tabClickFromParent.value);
        });
      } else {
        const param = {
          fR_ID: clickObj.value.FR_ID,
          fmT_ID: tabClickFromParent.value.FMT_ID,
          fR_TableField: formData.TableField,
          fR_RuleType: formData.RuleType,
          fR_Rule: formData.Rule,
          fR_Enable: formData.Enable,
          fR_Status: formData.Status,
          fR_Remark: formData.Remark
        };
        proxy.$vueAxios.put("Master_Base_FieldRule", param).then(() => {
          dialogSetting.visible = false;
          getTableData(tabClickFromParent.value);
        });
      }
    }
  });
};
// 搜索事件
const onSearchChange = () => {
  const filterData = tableSetting.sourthTableData.filter(
    data =>
      data.CName.toLowerCase().includes(searchString.value.toLowerCase()) ||
      data.FR_TableField.toLowerCase().includes(searchString.value.toLowerCase())
  );
  tableSetting.data = filterData;
};
// 将getTableData函数暴露给父组件
defineExpose({ getTableData });
</script>

<style scoped lang="scss">
.form-tab2 {
  height: calc(100% - 40px);
  .button-group {
    margin: 0 0 10px;
    .input-search {
      margin-right: 10px;
    }
  }
}
</style>
